<template>
  <div>
    <div class="head-container">
      <el-date-picker v-model="query.date" value-format="yyyy-MM-dd" type="date"
                      :picker-options="pickerOptions"
                      popper-class="picker-popper"
                      placeholder="选择日期"></el-date-picker>
      <el-time-picker v-model="query.time" value-format="HH:mm:ss" is-range range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"></el-time-picker>
      <el-button type="warning" size="mini" icon="el-icon-search" @click="search">查询</el-button>
      <el-button type="primary" size="mini" @click="animationStart">轨迹回放</el-button>
      <el-button type="primary" size="mini" icon="el-icon-download" @click="downloadExcel">导出</el-button>
    </div>
    <div class="map">
      <map-gis ref="map" @init="mapInit" />
    </div>
  </div>
</template>

<script>
import MapGis from '@/components/MapGis'
import { getGpsList } from '@/api/jf/equipmentDetialInfo'

import coordtransform from 'coordtransform'
import { getGpsDateList } from '@/api/jf/eqBiz'
import { download } from '@/api/data'
import { downloadFile } from '@/utils/index'
export default {
  name: '',
  components: { MapGis },
  props: {
    eqObj: {
      type: Object,
      default:function(){
        return null
      }
    }
  },
  data() {
    const _this = this
    return {
      badgeDate: ['2023-03-01', '2023-03-11', '2023-03-15'],
      pickerOptions: {
        cellClassName: (time) => {
          if (_this.badgeDate.includes(_this.parseTime(time, '{y}-{m}-{d}'))) {
            return 'badge'
          }
        }
      },
      eqCode:"",
      coordtransform,
      gpsPathList: [],
      marker: null,
      query: {
        date: null,
        time: null
      },
      // img: ''
    }
  },
  watch: {
    'eqObj': {
      handler(newVal, oldVal) {
        if(newVal.rcv_time) {
          this.query.eqCode = this.$route.params.eqCode
          this.query.date = this.dateFormat("YYYY-mm-dd", new Date(newVal.rcv_time))
          this.query.time = ["00:00:00", "23:59:59"]
          this.search()
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.eqCode = this.$route.params.eqCode
    //初始化日期标记
    getGpsDateList({eqCode:this.eqCode}).then(data => {
      this.badgeDate = [];
      const _this = this
      if(data.data && data.data.length > 0){
        data.data.forEach(function(obj){
          _this.badgeDate.push(obj.date)
        })
      }
    })
  },
  beforeCreate() {
    this.map && this.map.destroy()
  },
  beforeDestroy() {
    this.map && this.map.destroy()
  },
  methods: {
    search() {
      if (!this.query.date || !this.query.time) {
        return
      }
      this.map && this.map.destroy()
      this.$refs.map.aMapoader()
    },
    async mapInit(AMap, map) {
      if (!this.query.date && !this.query.time || !this.eqObj.rcv_time) {
        return
      }
      const params = {
        start_ts: new Date(this.query.date + ' ' + this.query.time[0]).getTime(),
        end_ts: new Date(this.query.date + ' ' + this.query.time[1]).getTime(),
        eq_code: this.eqCode
      }
      var result = (await getGpsList(params)).data
      const gpsPathList = result.gpsList
      const eqObj = result.eqObj
      if (gpsPathList.length === 0) return
      this.gpsPathList = gpsPathList.map((item) => {
        return this.coordtransform.wgs84togcj02(item.longitude, item.latitude)
      })
      const { Marker, Polyline, plugin, Pixel } = AMap
      const eqIcon1b = require('../../../assets/images/eq1_b.png')
      const eqIcon2b = require('../../../assets/images/eq2_b.png')
      const eqIcon3b = require('../../../assets/images/eq3_b.png')
      const eqIcon4b = require('../../../assets/images/eq4_b.png')
      const eqIcon5b = require('../../../assets/images/eq5_b.png')

      let eqIcon
      if(eqObj.eq_type == "插秧机") {
        eqIcon = eqIcon2b
      }
      else if(eqObj.eq_type == "收割机") {
        eqIcon = eqIcon1b
      }
      else if(eqObj.eq_type == "拖拉机") {
        eqIcon = eqIcon3b
      }
      else if(eqObj.eq_type == "直播机") {
        eqIcon = eqIcon3b
      }
      else {
        eqIcon = eqIcon4b
      }

      plugin('AMap.MoveAnimation', () => {
        this.marker = new Marker({
          map: map,
          position: this.gpsPathList[0],
          offset: new Pixel(-30, -80),
          autoRotation: true,
          icon: eqIcon
        })
        new Polyline({
          map,
          path: this.gpsPathList,
          showDir: false,
          strokeColor: '#28F',
          strokeWeight: 6, // 线宽
          strokeStyle: 'solid',
          icon: eqIcon,
          strokeOpacity: 1
        })
        const passedPolyline = new Polyline({
          map,
          strokeColor: '#28F',
          strokeWeight: 6 // 线宽
        })
        this.marker.on('moving', (e) => {
          passedPolyline.setPath(e.passedPath)
        })
        map.setFitView()
      })
    },
    animationStart() {
      this.marker.moveAlong(this.gpsPathList, {
        duration: 500,
        autoRotation: false
      })
    },
    // 入参 fmt-格式 date-日期
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
      };
      return fmt;
    },
    parseTime(time, cFormat) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string')) {
          if ((/^[0-9]+$/.test(time))) {
            time = parseInt(time)
          } else {
            time = time.replace(new RegExp(/-/gm), '/')
          }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
        return value.toString().padStart(2, '0')
      })
      return time_str
    },
    downloadExcel() {
      if (!this.query.date && !this.query.time || !this.eqObj.rcv_time) {
        return
      }
      const params = {
        start_ts: new Date(this.query.date + ' ' + this.query.time[0]).getTime(),
        end_ts: new Date(this.query.date + ' ' + this.query.time[1]).getTime(),
        eq_code: this.eqCode
      }
      download('api/v2/biz/eq/getGps/download', params).then(result => {
        downloadFile(result, 'GPS数据', 'xlsx')
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 780px;
}
#map-container {
  width: 100%;
  height: 100%;
}
</style>

<style lang="scss">
#map-container {
  .amap-copyright,
  .amap-logo {
    display: none !important;
  }

  .amap-marker-label {
    border: unset;
    background: unset;
    color: white;
    cursor: pointer;
  }
}
</style>

<style>
.picker-popper .el-date-table .badge::after {
  position: absolute;
  content: "";
  right: 4px;
  top: 4px;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: red;
}
</style>
